/********************************************************************************
  * @file    showdirlineedit.cpp
  * @author  Lun Li
  * @version V1.5.0
  * @date    2022.4.10
  * @brief   This file provides all the ShowDirLineEdit functions.
  ******************************************************************************/

#include "showdirlineedit.h"

ShowDirLineEdit::ShowDirLineEdit(const QString &labelText, const QString &buttonText, QWidget *parent)
    : QWidget(parent),
      m_lineEdit(new QLineEdit(this)),
      m_button(new QPushButton(buttonText, this))
{
    setLayout(new NoMarginVBoxLayout);
    QWidget *hWidget = new QWidget(this);
    hWidget->setLayout(new NoMarginHBoxLayout);
    hWidget->layout()->addWidget(m_lineEdit);
    hWidget->layout()->addWidget(m_button);
    layout()->addWidget(new QLabel(labelText));
    layout()->addWidget(hWidget);
    connectSignals();
}

ShowDirLineEdit::ShowDirLineEdit(QLabel *label, QWidget *parent)
    : QWidget(parent),
      m_lineEdit(new QLineEdit(this)),
      m_button(nullptr)
{
    setLayout(new NoMarginVBoxLayout);
    layout()->addWidget(label);
    layout()->addWidget(m_lineEdit);
    connectSignals();
}

ShowDirLineEdit::ShowDirLineEdit(const QString &buttonText, QWidget *parent)
    : QWidget(parent),
      m_lineEdit(new QLineEdit(this)),
      m_button(new QPushButton(buttonText, this))
{
    setLayout(new NoMarginHBoxLayout);
    layout()->addWidget(m_lineEdit);
    layout()->addWidget(m_button);
    connectSignals();
}

ShowDirLineEdit::ShowDirLineEdit(QWidget *parent)
    : QWidget(parent),
      m_button(nullptr)
{
    m_lineEdit = new QLineEdit(this);
    setLayout(new NoMarginHBoxLayout);
    layout()->addWidget(m_lineEdit);
    connectSignals();
}

void ShowDirLineEdit::setText(const QString &text)
{
    m_lineEdit->setText(QDir::toNativeSeparators(text));
    m_text = text;
}

QString ShowDirLineEdit::text() const
{
    return m_text;
}

QPushButton *ShowDirLineEdit::button() const
{
    return m_button;
}

void ShowDirLineEdit::connectSignals()
{
    connect(m_lineEdit, &QLineEdit::textChanged, this, [=](const QString &text) {
        m_text = QDir::fromNativeSeparators(text);
        emit textChanged(m_text);
    });
    connect(m_lineEdit, &QLineEdit::textEdited, this, [=](const QString &text) {
        m_text = QDir::fromNativeSeparators(text);
        emit textEdited(m_text);
    });
}
